package com.dimbottom.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dimbottom.util.Connection;
import com.dimbottom.util.InfoParser;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.IOException;

/**
 * 服务类
 */
public class AutoSignInService {

    private static final Logger logger = Logger.getLogger(AutoSignInService.class);

    Connection connection = new Connection();

    /**
     * @param studentCode 学号
     * @return 以往提交的信息
     * @throws IOException 模板文件不存在
     */
    public JSONObject query(String studentCode) throws IOException {
        InfoParser infoParser = new InfoParser();
        InfoParser.BasicInfo info = infoParser.loadInfo("query");
        String query = connection.doPost(info.getUrl(), info.getHeaders(), info.getContent());
        JSONObject res = new JSONObject();
        if (query != null) {
            JSONObject json = JSON.parseObject(query);
            if (json.get("errors") != null) {
                logger.error("查询时出现错误，请检查配置文件是否被修改，错误信息:" + json.get("errors"));
                return null;
            }

            JSONObject variables = json.getJSONObject("data").getJSONArray("atschoolsList").getJSONObject(0);
            if (variables.size() == 0) {
                logger.warn("学号[" + studentCode + "]未查询到结果，请检查学号是否正确");
                return null;
            }
            /*删除无关的数据*/
            variables.remove("id");
            variables.remove("date");
            variables.remove("tzCreate");
            res.put("variables", variables);
        } else {
            logger.error("出现内部错误，请检查网络连接，或其他操作。");
            return null;
        }
        return res;
    }

    /**
     * @param studentCode 学号
     * @throws IOException 模板文件不存在
     */
    public void submit(String studentCode) throws IOException {
        if (StringUtils.isBlank(studentCode)) {
            logger.warn("学号为空，自动提交失败！");
            return;
        }
        logger.info("学号[" + studentCode + "]正在查询提交记录");
        JSONObject content = query(studentCode);
        InfoParser infoParser = new InfoParser();
        InfoParser.BasicInfo info = infoParser.loadInfo("submit");
        if (content != null)
            info.setSubmitVariables(content);
        else {
            logger.info("学号[" + studentCode + "]查询失败，使用在校模板提交");
        }
        info.setSubmitStudentCode(studentCode);
        logger.info("学号[" + studentCode + "]开始自动签到，提交信息如下：" + info.getContent());
        String res = connection.doPost(info.getUrl(), info.getHeaders(), info.getContent());
        JSONObject parse = JSON.parseObject(res);
        if (parse.get("errors") != null) {
            logger.error("提交时出现错误，自动签到失败，错误信息:" + parse.get("errors"));
            return;
        }
        logger.info("学号[" + studentCode + "]自动签到成功");

    }

}
